package com.hitrust.gs.action.productTiptopStock;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.servlet.ServletOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import system.LoginContext;

import com.hitrust.gs.business.GSProductTiptopStockProcesser;
import com.hitrust.gs.business.GSUniteGwProcessor;
import com.hitrust.gs.dao.GSWarehouseStorageConfigDAO;
import com.hitrust.gs.form.ProductNotPurchaseForm;
import com.hitrust.gs.form.WarehouseMaxStorageCofigForm;
import com.hitrust.gs.lib.GSBaseConstants;
import com.hitrust.gs.service.GSBaseAction;
import com.hitrust.gs.service.GSBaseForm;
import com.hitrust.gs.service.GSBaseManager;
import com.hitrust.gs.util.exception.GSException;
import com.hitrust.gs.util.page.ResultProcess;
import com.hitrust.gs.vo.ProductTiptopStockVO;
import com.hitrust.gs.vo.ProductUpdatePicVO;
import com.hitrust.gs.vo.WarehouseMaxStorageCofigVO;

import framework.core.DateUtil;

public class GSProductTiptopStockAction extends GSBaseAction {
	public String execute(GSBaseForm aForm) throws Exception {

		String path = aForm.getRequest().getServletPath();
		GSWarehouseStorageConfigDAO dao = new GSWarehouseStorageConfigDAO();
		
		if ("/A300001.do".equals(path)) {
			toPage(aForm);
	        
	        
		}else if ("/A3000011.do".equals(path)){
			pageSelect(aForm);
			toPage(aForm);
		}else if ("/A3000013.do".equals(path)){ 
			
		}else if ("/A3000015.do".equals(path)){
			WarehouseMaxStorageCofigForm tForm = (WarehouseMaxStorageCofigForm)aForm;
			WarehouseMaxStorageCofigVO wmcVO = new WarehouseMaxStorageCofigVO();
			wmcVO.m_concentricity_code = tForm.getM_concentricity_code();
			wmcVO.m_product_name = tForm.getM_product_name();
			wmcVO.m_model = tForm.getM_model();
			wmcVO.m_spec = tForm.getM_spec();
			wmcVO.m_drawing_piece_code = tForm.getM_drawing_piece_code();
			wmcVO.m_provider_code = tForm.getM_provider_code();
			wmcVO.m_status = tForm.getM_status();
			wmcVO.m_currentWarehouseCode = tForm.getM_currentWarehouseCode();	
			GSProductTiptopStockProcesser ordProcesser = new GSProductTiptopStockProcesser();
		    ArrayList maxStorageList = ordProcesser.getWareHouseMaxStorageConfigAll(wmcVO);
		    //导出excel
		    exportDetailStatistic(maxStorageList,aForm);
		}else if("/A300002.do".equals(path)){
			toPage(aForm);
			
		}else if("/A3000021.do".equals(path)){
			toPage(aForm);
			pageSelect(aForm);
		}else if("/A300003.do".equals(path)){// 产品不可采购可出库管理
			
			
		}else if ("/A3000032.do".equals(path)) {// 产品不可采购可出库  导入
			
		}else if("/A3000031.do".equals(path)) { // 产品不可采购可出库  查询
			pageSelectToProductNotPur(aForm);
			
		}else if("/A3000035.do".equals(path)){//产品不可采购可出库  进入导入页面
			
		}else if("/A3000033.do".equals(path)){//产品不可采购可出库  导出
			ProductNotPurchaseForm tForm = (ProductNotPurchaseForm)aForm;
			GSProductTiptopStockProcesser ordProcesser = new GSProductTiptopStockProcesser();
		    ArrayList productList = ordProcesser.getProductNotPurchaseAll(tForm);
		    //导出excel
		    exportNotPur(productList,aForm);
		}else if("/A300004.do".equals(path)){//产品不可采购可出库  审批
			
		}else if("/A3000041.do".equals(path)){//产品不可采购可出库  审批  查询
			pageSelectToProductNotPur(aForm);
		}else if("/A3000042.do".equals(path)){//产品不可采购可出库  审批  通过
			pass(aForm);
			pageSelectToProductNotPur(aForm);
		}else if("/A3000043.do".equals(path)){//产品不可采购可出库  审批  不通过
			noPass(aForm);
			pageSelectToProductNotPur(aForm);
		}else if ("/A3000051.do".equals(path)) { //老库存编码 导入页面
			
		}
		
		
		return GSBaseConstants.FORWARD_SUCCESS;

	}
	
	//审批  通过
	private void pass(GSBaseForm aForm){
		try {
				ProductNotPurchaseForm tForm = (ProductNotPurchaseForm)aForm;
				String[] passArr = tForm.getIndexs();
				GSProductTiptopStockProcesser ordProcesser = new GSProductTiptopStockProcesser();
				//登录人的信息
				LoginContext loginContext = (LoginContext)aForm.getSession().getAttribute(GSBaseConstants.LOGIN);
				String userName = loginContext.getUser().getName();
				String userId = loginContext.getUser().getId();
				String currentDateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
								.format(new java.util.Date(System.currentTimeMillis()));
				for (int i = 0; i < passArr.length; i++) {
					
						ordProcesser.passProductUpdatePic(passArr[i],userName,userId,currentDateStr);
					
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//审批  不通过
	private void noPass(GSBaseForm aForm){
		ProductNotPurchaseForm tForm = (ProductNotPurchaseForm)aForm;
		try {
				String[] passArr = tForm.getIndexs();
				//登录人的信息
				LoginContext loginContext = (LoginContext)aForm.getSession().getAttribute(GSBaseConstants.LOGIN);
				String userName = loginContext.getUser().getName();
				String userId = loginContext.getUser().getId();
				String currentDateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
								.format(new java.util.Date(System.currentTimeMillis()));
				GSProductTiptopStockProcesser ordProcesser = new GSProductTiptopStockProcesser();
				for (int i = 0; i < passArr.length; i++) {
					ordProcesser.noPassProductUpdatePic(passArr[i],userName,userId,currentDateStr);				
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void pageSelectToProductNotPur(GSBaseForm aForm){
		try {
			String[] tStr = null;
			ProductNotPurchaseForm tForm = (ProductNotPurchaseForm)aForm;
			String bb = "";
			if(aForm.getRequest().getParameter("m_mypagesize")!=null){
				bb = aForm.getRequest().getParameter("m_mypagesize")+"";
			}
			if(bb.equals("20")||bb.equals("50")){
				//pageContext.setAttribute("pageSize",(String)request.getAttribute("pageSize"));
				String tPage = bb;
		        aForm.setPageSize(Integer.parseInt(tPage));
		        tForm.setPageSize(Integer.parseInt(tPage));
		        aForm.getRequest().setAttribute("m_mypagesize",tPage);
		        tForm.getRequest().setAttribute("m_mypagesize", tPage);
				tStr = this.getPageParamsToProNotPur2(aForm, tForm);

			}else{
				tStr = this.getPageParamsToProNotPur(aForm, tForm);
			}
			
			GSProductTiptopStockProcesser ordProcesser = new GSProductTiptopStockProcesser();
		    ArrayList maxStorageList = ordProcesser.getProductNotPurchase(tForm, Integer.parseInt(tStr[0]), Integer.parseInt(tStr[1]));
	        ResultProcess tRsProc = new ResultProcess();
	        tRsProc.setResult(maxStorageList);
	        tForm.getRequest().setAttribute("maxStorageList", tRsProc);
	        // 存储分页参数
	        tForm.getRequest().setAttribute("pageSize", tStr[1]);
	        tForm.getRequest().setAttribute("totalRecords", tStr[2]);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    /**
     * 取得分页参数
     * 
     *            组织ArrayList对象
     * @return
     * @throws Exception
     */
    private String[] getPageParamsToProNotPur(GSBaseForm aForm, ProductNotPurchaseForm tForm) throws Exception {
        String tStr[] = new String[3];
        int totalRecords;
        int pageNo;
        int pageSize;
        String tPage = GSBaseConstants.tPage;
        GSProductTiptopStockProcesser ordProcesser = new GSProductTiptopStockProcesser();
        // 根据页面传入的查询参数查询信息
        if (aForm.getChoice() == null || aForm.getChoice().equals("")) {
            totalRecords = ordProcesser.getProductNotPurchaseCount(tForm);

            // 取得系统默认的页大小
            pageSize = Integer.parseInt(tPage);
            // PageNo=1
            pageNo = 1;
            int n = (totalRecords % pageSize == 0) ? totalRecords / pageSize : totalRecords / pageSize + 1;
            if (pageNo > n) {
                pageNo = n;
            }
            tStr[0] = "" + pageNo;
            tStr[1] = "" + pageSize;
            tStr[2] = "" + totalRecords;
        } else {
            tStr = GSBaseManager.getPageNoAndPageSize(aForm);
        }
        return tStr;
    }
    
    private String[] getPageParamsToProNotPur2(GSBaseForm aForm, ProductNotPurchaseForm tForm) throws Exception {
        String tStr[] = new String[3];
        int totalRecords;
        int pageNo;
        int pageSize;
        String tPage = aForm.getRequest().getParameter("m_mypagesize")+"";
         GSProductTiptopStockProcesser ordProcesser = new GSProductTiptopStockProcesser();
        // 根据页面传入的查询参数查询信息
        if (aForm.getChoice() == null || aForm.getChoice().equals("")) {
            totalRecords = ordProcesser.getProductNotPurchaseCount(tForm);

            // 取得系统默认的页大小
            pageSize = Integer.parseInt(tPage);
            // PageNo=1
            pageNo = 1;
            int n = (totalRecords % pageSize == 0) ? totalRecords / pageSize : totalRecords / pageSize + 1;
            if (pageNo > n) {
                pageNo = n;
            }
            tStr[0] = "" + pageNo;
            tStr[1] = "" + pageSize;
            tStr[2] = "" + totalRecords;
        } else {
            tStr = GSBaseManager.getPageNoAndPageSize(aForm);
        }
        return tStr;
    }
	
	
	
	private void toPage(GSBaseForm aForm) throws GSException{
		 LoginContext loginContext = (LoginContext)aForm.getSession().getAttribute(GSBaseConstants.LOGIN);
	     GSUniteGwProcessor processer = new GSUniteGwProcessor();
		 ArrayList ary = processer.queryCompany(loginContext.getLoginWarehouseCode(),loginContext.getLoginWarehouseCode());
	     aForm.getRequest().setAttribute("organdaddr",ary);
	}
	
	private void pageSelect(GSBaseForm aForm){
	  try {
			WarehouseMaxStorageCofigForm tForm = (WarehouseMaxStorageCofigForm)aForm;
			WarehouseMaxStorageCofigVO wmcVO = new WarehouseMaxStorageCofigVO();
			wmcVO.m_concentricity_code = tForm.getM_concentricity_code();
			wmcVO.m_product_name = tForm.getM_product_name();
			wmcVO.m_model = tForm.getM_model();
			wmcVO.m_spec = tForm.getM_spec();
			wmcVO.m_drawing_piece_code = tForm.getM_drawing_piece_code();
			wmcVO.m_provider_code = tForm.getM_provider_code();
			wmcVO.m_status = tForm.getM_status();
			wmcVO.m_currentWarehouseCode = tForm.getM_currentWarehouseCode();	
			String[] tStr = this.getPageParams(aForm, wmcVO);
			
			GSProductTiptopStockProcesser ordProcesser = new GSProductTiptopStockProcesser();
		    ArrayList maxStorageList = ordProcesser.getWareHouseMaxStorageConfig(wmcVO, Integer.parseInt(tStr[0]), Integer.parseInt(tStr[1]));
	        ResultProcess tRsProc = new ResultProcess();
	        tRsProc.setResult(maxStorageList);
	        tForm.getRequest().setAttribute("maxStorageList", tRsProc);
	        // 存储分页参数
	        tForm.getRequest().setAttribute("pageSize", tStr[1]);
	        tForm.getRequest().setAttribute("totalRecords", tStr[2]);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	
    /**
     * 取得分页参数
     * 
     *            组织ArrayList对象
     * @return
     * @throws Exception
     */
    private String[] getPageParams(GSBaseForm aForm, WarehouseMaxStorageCofigVO wmcVO) throws Exception {
        String tStr[] = new String[3];
        int totalRecords;
        int pageNo;
        int pageSize;
        String tPage = GSBaseConstants.tPage;
        GSProductTiptopStockProcesser ordProcesser = new GSProductTiptopStockProcesser();
        // 根据页面传入的查询参数查询信息
        if (aForm.getChoice() == null || aForm.getChoice().equals("")) {
            totalRecords = ordProcesser.getWareHouseMaxStorageConfigCount(wmcVO);

            // 取得系统默认的页大小
            pageSize = Integer.parseInt(tPage);
            // PageNo=1
            pageNo = 1;
            int n = (totalRecords % pageSize == 0) ? totalRecords / pageSize : totalRecords / pageSize + 1;
            if (pageNo > n) {
                pageNo = n;
            }
            tStr[0] = "" + pageNo;
            tStr[1] = "" + pageSize;
            tStr[2] = "" + totalRecords;
        } else {
            tStr = GSBaseManager.getPageNoAndPageSize(aForm);
        }
        return tStr;
    }
    
    
    private void exportDetailStatistic(ArrayList maxStorageList,GSBaseForm aForm) throws Exception
    {
        HSSFWorkbook tWb = new HSSFWorkbook();
        HSSFSheet tSheet = tWb.createSheet();
        tWb.setSheetName(0,"产品最高库存设置",HSSFCell.ENCODING_UTF_16);
        HSSFRow tRow = tSheet.createRow((short)0);
        HSSFCell tCell0  = createCell(tWb,tRow,(short)0, "集中编码");
        HSSFCell tCell1  = createCell(tWb,tRow,(short)1, "产品名称");
        HSSFCell tCell2  = createCell(tWb,tRow,(short)2, "单位");
        HSSFCell tCell3  = createCell(tWb,tRow,(short)3, "单价");
        HSSFCell tCell4  = createCell(tWb,tRow,(short)4, "规格");
        HSSFCell tCell5  = createCell(tWb,tRow,(short)5, "型号");
        HSSFCell tCell6  = createCell(tWb,tRow,(short)6, "图鉴号");
        HSSFCell tCell7  = createCell(tWb,tRow,(short)7, "供应商");
        HSSFCell tCell8  = createCell(tWb,tRow,(short)8, "最高库存");
        HSSFCell tCell9  = createCell(tWb,tRow,(short)9, "所属仓库");
        HSSFCell tCell10  = createCell(tWb,tRow,(short)10, "最后更新时间");
        HSSFCell tCell11 = createCell(tWb,tRow,(short)11,"状态");
        

        
        for(int i=0;i<maxStorageList.size();i++)
        {
        	ProductTiptopStockVO pts = (ProductTiptopStockVO)maxStorageList.get(i);
            HSSFRow row = tSheet.createRow((short)i+1);
            HSSFCell cell0  = createCell(tWb,row,(short)0, pts.getConcentricity_code());
            HSSFCell cell1  = createCell(tWb,row,(short)1, pts.getName());
            HSSFCell cell2  = createCell(tWb,row,(short)2, pts.getProduct_unit());
            HSSFCell cell3  = createCell(tWb,row,(short)3, pts.getUnit_price());
            HSSFCell cell4  = createCell(tWb,row,(short)4, pts.getSpec());
            HSSFCell cell5  = createCell(tWb,row,(short)5, pts.getModel());
            HSSFCell cell6  = createCell(tWb,row,(short)6, pts.getDrawing_piece_code());
            HSSFCell cell7  = createCell(tWb,row,(short)7, pts.getProvidername());
            HSSFCell cell8  = createCell(tWb,row,(short)8, pts.getMax_count());
            HSSFCell cell9  = createCell(tWb,row,(short)9, pts.getWarehouse_code());
            HSSFCell cell10  = createCell(tWb,row,(short)10, pts.getLast_update_time());
            HSSFCell cell11 = createCell(tWb,row,(short)11,pts.getStatus());
           
        }
        

        
        DateUtil date = new DateUtil();
        String year = date.getYear() + "";
        String month = date.getMonth() + "";
        if (date.getMonth() < 10) month = "0" + date.getMonth();
        String day = date.getDay() + "";
        if (date.getDay() < 10) day = "0" + date.getDay();
        String hour = date.getHour() + "";
        if (date.getHour() < 10) hour = "0" + date.getHour();
        String minute = date.getMinute() + "";
        if (date.getMinute() < 10) minute = "0" + date.getMinute();
        String second = date.getSecond() + "";
        if (date.getSecond() < 10) second = "0" + date.getSecond();
        
        String fileName = "maxStorageConfig" + year + "_" + month + "_" + day + "_" + hour + "_" + minute + "_" + second + ".xls";
      
        aForm.getResponse().setContentType("application/ms-excel");
        aForm.getResponse().addHeader("Content-disposition", "filename="+fileName);
        ServletOutputStream out = aForm.getResponse().getOutputStream();
        tWb.write(out);
        out.flush();
        out.close();
    }
    
	private HSSFCell createCell(HSSFWorkbook aWb, HSSFRow aRow, short column,String aValue){
        HSSFCell tCell = aRow.createCell(column);
        tCell.setEncoding(HSSFCell.ENCODING_UTF_16);
        tCell.setCellValue(aValue);
        return tCell;
    }
	
	
	
	/**
     * 产品不可采购可出库管理 取得分页参数
     * 
     *            组织ArrayList对象
     * @return
     * @throws Exception
     */
    private String[] getProductPageParams(GSBaseForm aForm, ProductNotPurchaseForm proForm) throws Exception {
        String tStr[] = new String[3];
        int totalRecords;
        int pageNo;
        int pageSize;
        String tPage = GSBaseConstants.tPage;
        GSProductTiptopStockProcesser ordProcesser = new GSProductTiptopStockProcesser();
        // 根据页面传入的查询参数查询信息
        if (aForm.getChoice() == null || aForm.getChoice().equals("")) {
            totalRecords = ordProcesser.getProductNotPurchaseCount(proForm);

            // 取得系统默认的页大小
            pageSize = Integer.parseInt(tPage);
            // PageNo=1
            pageNo = 1;
            int n = (totalRecords % pageSize == 0) ? totalRecords / pageSize : totalRecords / pageSize + 1;
            if (pageNo > n) {
                pageNo = n;
            }
            tStr[0] = "" + pageNo;
            tStr[1] = "" + pageSize;
            tStr[2] = "" + totalRecords;
        } else {
            tStr = GSBaseManager.getPageNoAndPageSize(aForm);
        }
        return tStr;
    }
	
    /**
     * 产品不可采购可出库管理 导出excel
     * 
     * @return
     * @throws Exception
     */
    private void exportNotPur(ArrayList ProductList,GSBaseForm aForm) throws Exception
    {
        HSSFWorkbook tWb = new HSSFWorkbook();
        HSSFSheet tSheet = tWb.createSheet();
        tWb.setSheetName(0,"产品不可采购可出库",HSSFCell.ENCODING_UTF_16);
        HSSFRow tRow = tSheet.createRow((short)0);
        HSSFCell tCell0  = createCell(tWb,tRow,(short)0, "集中编码");
        HSSFCell tCell1  = createCell(tWb,tRow,(short)1, "产品名称");
        HSSFCell tCell2  = createCell(tWb,tRow,(short)2, "规格");
        HSSFCell tCell3  = createCell(tWb,tRow,(short)3, "型号");
        HSSFCell tCell4  = createCell(tWb,tRow,(short)4, "图件号");
        HSSFCell tCell5  = createCell(tWb,tRow,(short)5, "供应商");
        HSSFCell tCell6  = createCell(tWb,tRow,(short)6, "区域分类");
        HSSFCell tCell7  = createCell(tWb,tRow,(short)7, "招标分类");
        HSSFCell tCell8  = createCell(tWb,tRow,(short)8, "启用日期");
        HSSFCell tCell9 = createCell(tWb,tRow,(short)9,"是否启用");
        HSSFCell tCell10 = createCell(tWb,tRow,(short)10,"审批状态");
        HSSFCell tCell11 = createCell(tWb,tRow,(short)11,"创建人");
        HSSFCell tCell12 = createCell(tWb,tRow,(short)12,"创建时间");
        HSSFCell tCell13 = createCell(tWb,tRow,(short)13,"审批人");
        HSSFCell tCell14 = createCell(tWb,tRow,(short)14,"审批时间");
        
        for(int i=0;i<ProductList.size();i++)
        {
        	ProductUpdatePicVO pts = (ProductUpdatePicVO)ProductList.get(i);
            HSSFRow row = tSheet.createRow((short)i+1);
            HSSFCell cell0  = createCell(tWb,row,(short)0, pts.getConcentricity_code());
            HSSFCell cell1  = createCell(tWb,row,(short)1, pts.getName());
            HSSFCell cell2  = createCell(tWb,row,(short)2, pts.getSpec());
            HSSFCell cell3  = createCell(tWb,row,(short)3, pts.getModel());
            HSSFCell cell4  = createCell(tWb,row,(short)4, pts.getM_drawing_piece_code());
            HSSFCell cell5  = createCell(tWb,row,(short)5, pts.getProvidername());
            HSSFCell cell6  = createCell(tWb,row,(short)6, pts.getAreatype());
            HSSFCell cell7  = createCell(tWb,row,(short)7, pts.getType_name());
            HSSFCell cell8  = createCell(tWb,row,(short)8, pts.getEnabled_time());
            HSSFCell cell9  = createCell(tWb,row,(short)9, pts.getStatus());
            HSSFCell cell10  = createCell(tWb,row,(short)10, pts.getAuditing_status());
            HSSFCell cell11 = createCell(tWb,row,(short)11,pts.getCreate_user());
            HSSFCell cell12 = createCell(tWb,row,(short)12,pts.getCreate_time());
            HSSFCell cell13 = createCell(tWb,row,(short)13,pts.getAuditing_user());
            HSSFCell cell14 = createCell(tWb,row,(short)14,pts.getAuditing_time());
       
        }
        

        
        DateUtil date = new DateUtil();
        String year = date.getYear() + "";
        String month = date.getMonth() + "";
        if (date.getMonth() < 10) month = "0" + date.getMonth();
        String day = date.getDay() + "";
        if (date.getDay() < 10) day = "0" + date.getDay();
        String hour = date.getHour() + "";
        if (date.getHour() < 10) hour = "0" + date.getHour();
        String minute = date.getMinute() + "";
        if (date.getMinute() < 10) minute = "0" + date.getMinute();
        String second = date.getSecond() + "";
        if (date.getSecond() < 10) second = "0" + date.getSecond();
        
        String fileName = "product" + year + "_" + month + "_" + day + "_" + hour + "_" + minute + "_" + second + ".xls";
      
        aForm.getResponse().setContentType("application/ms-excel");
        aForm.getResponse().addHeader("Content-disposition", "filename="+fileName);
        ServletOutputStream out = aForm.getResponse().getOutputStream();
        tWb.write(out);
        out.flush();
        out.close();
    }
}

